<?php

class ProfileController extends BaseController {
    
    public $canModerRevCom = false;
    public $canModerRev = false;
    public $seeAnonymRev = false;
    
    public function init() {
        if(!Yii::app()->request->isAjaxRequest && !isset($_POST['Reviews'])) Yii::app()->user->setState('xuploadFiles', array());
        $this->options = Yii::app()->db->createCommand(array('select'=>'val, name', 'from'=>'options'))->queryAll();
        Yii::app()->bootstrap->registerCoreCss();
        Yii::app()->bootstrap->registerYiiCss();
        Yii::app()->bootstrap->registerCoreScripts();
    }
    
    public function actions() {
        return array(
            'upload'=>array(
                'class'=>'application.actions.XImgUploadAction',
                'path' =>Yii::app()->getBasePath() . "/../images/uploads/reviews",
                'publicPath' => Yii::app() -> getBaseUrl() . "/images/uploads/reviews",
                'secureFileNames'=>true,
                'subfolderVar' => false,
                'imagesTable'=>'reviews_images',
            ),
        );
    }
    
    private function checkIsReviewModerator() {
        if(Yii::app()->user->isGuest) return 0;
        $user = Yii::app()->user->getAllUserInfo();
        if(Yii::app()->user->checkAccess('redactor') || Yii::app()->user->checkAccess('admin') || $user['editComment']) $this->canModerRevCom = true;
        if(Yii::app()->user->checkAccess('redactor') || Yii::app()->user->checkAccess('admin') || $user['editReview']) $this->canModerRev = true;
        if(Yii::app()->user->checkAccess('redactor') || Yii::app()->user->checkAccess('admin') || $user['seeAnonim']) $this->seeAnonymRev = true;
    }
    
    public function actionIndex($partnerUrl, $catId, $filter=0) {
        $model = new Reviews();
        if(isset($_POST['Reviews'])) {
            $model->attributes = $_POST['Reviews'];
            if($model->save()) $this->redirect(array('profile/preview', 'url'=>$model->url));
            else Yii::app()->user->setState('xuploadFiles', array());
        }
        $errorModel = new ErrorReporting();
        if(isset($_POST['ErrorReporting'])) {
            if($errorModel->save()) $this->refresh();
        }
        $cat = Yii::app()->db->createCommand()->select('catId, name, reviewRules, reviewRating1, reviewRating2, reviewRating3, reviewRating4, revRat1About, revRat2About, revRat3About, revRat4About, ratingRules')->from('partners_cat')->where("catId=$catId")->queryRow();
        if(empty($cat)) throw new CHttpException(404, 'Не найдено указанной записи');
        $partner = Yii::app()->db->createCommand()->select('p.fieldName, p.name, p.url, p.partnerid, p.delegate1, p.editorMark, p.openDate, p.delegate2, p.keywords, p.title, p.about, p.type, p.refLink, s.mean, s.field1, s.field2, s.field3, s.field4')->leftJoin('partners_cat_score s', 's.partnerId=p.partnerId')->from('partners p')->where('p.url="'.$partnerUrl.'" and p.catId='.$cat['catId'])->queryRow();
        if(empty($partner)) throw new CHttpException(404, 'Не найдено указанной записи');
        $this->brending('partner', $partner['partnerid'], $catId);
        $relProfiles = Yii::app()->db->createCommand()->select('*')->from('partners_relprofiles')->where("partnerid=".$partner['partnerid'])->queryAll();
        $sortRatings = Yii::app()->db->createCommand()->select('r.type, r.val, cr.val as catVal, cr.type as catType')->from('partners_ratings r')->join('partners_catraitings cr', 'cr.catRatingId=r.catRatingId')->where("r.partnerid=".$partner['partnerid'])->order('r.id')->queryAll();
        
        $delegates = Yii::app()->db->createCommand()->select('logDate, login, displayName, avatar, userid')->from('users')->where("userId IN(".$partner['delegate1'].", ".$partner['delegate2'].")")->queryAll();
        $revRatings = Yii::app()->db->createCommand()->select('*')->from('partners_ad_rev_rat t')->where('catId='.$cat['catId'])->queryAll();
        $partnersTextScore = Yii::app()->db->createCommand()->select('*')->from('partners_text_score')->where('partnerId='.$partner['partnerid'])->queryAll();
        
        $filterCondition = array('bad'=>"`partnerid`=".$partner['partnerid']." AND `averageRating`<5 AND (`status`=\"Одобрен\" OR `status`=\"Сомнительный\")", 'inert'=>"`partnerid`=".$partner['partnerid']." AND `averageRating` IN(5,6,7) AND (`status`=\"Одобрен\" OR `status`=\"Сомнительный\")", 'good'=>"`partnerid`=".$partner['partnerid']." AND `averageRating`>7 AND (`status`=\"Одобрен\" OR `status`=\"Сомнительный\")");        
        $pagination = new CPagination(Reviews::model()->count($filter ? $filterCondition[$filter] : "`partnerid`=".$partner['partnerid']." AND (`status`=\"Одобрен\" OR `status`=\"Сомнительный\")"));
        $pagination->setPageSize(!empty($this->options) ? $this->options['0']['name'] : 10);
        $count = Yii::app()->db->createCommand("SELECT COUNT(case when `averageRating`<5 and `status`=\"Одобрен\" then 1 else null end) as bad, COUNT(case when `averageRating`>4 and `averageRating`<8 and `status`=\"Одобрен\" then 1 else null end) as inert, COUNT(case when `averageRating`>7 and `status`=\"Одобрен\" then 1 else null end) as good, COUNT(case when `status`=\"Сомнительный\" then 1 else null end) as unreliable FROM `reviews` WHERE partnerid=".$partner['partnerid'].' AND (`status`="Одобрен" OR `status`="Сомнительный")')->queryRow();
        $reviews = Yii::app()->db->createCommand()->select('r.date, r.countComments, r.text, r.title, r.userIp, r.redactorNotice, r.url, r.revId, r.status, r.isAnonym, u.login, u.displayName, u.avatar, u.userid')->from('reviews r')->join('users u', 'u.userid=r.userId')->where($filter ? $filterCondition[$filter] : "`partnerid`=".$partner['partnerid']." AND (`status`=\"Одобрен\" OR `status`=\"Сомнительный\")")->limit($pagination->getLimit())->offset($pagination->getOffset())->order('r.revId asc')->queryAll();
        $subCats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where('partnerid='.$partner['partnerid'])->queryAll();
        if(!empty($reviews)) {
            $rId = array();
            foreach ($reviews as $r) $rId[] = $r['revId'];
            $revRat = Yii::app()->db->createCommand()->select('*')->from('reviews_ratings')->where(array('in', 'revId', $rId))->order('id')->queryAll();
            $revImages = Yii::app()->db->createCommand()->select('*')->from('reviews_images')->where(array('in', 'revId', $rId))->order('imgId')->queryAll();
            $revDelegateUns = Yii::app()->db->createCommand()->select('rc.*, u.login, u.displayName, u.avatar')->from('reviews_comments rc')->join('users u', 'u.userid=rc.userId')->where('revId in('.implode(',', $rId).') and isDelegate=1')->queryAll();
            for($l=0; $l<count($reviews); $l++) {
                for($i=0; $i<count($revRat); $i++) {
                    if($reviews[$l]['revId'] == $revRat[$i]['revId']) $reviews[$l]['revRatings'][] = $revRat[$i];
                }
                for($i=0; $i<count($revImages); $i++) {
                    if($reviews[$l]['revId'] == $revImages[$i]['revId']) $reviews[$l]['images'][] = $revImages[$i];
                }
                for($i=0; $i<count($revDelegateUns); $i++) {
                    if($revDelegateUns[$i]['revId'] == $reviews[$l]['revId']) $reviews[$l]['delegUns'] = $revDelegateUns[$i];
                }
            }
        }
        if(!Yii::app()->user->isGuest) {
            $newRevTime = time()-1200;
            $userNewReview = Yii::app()->db->createCommand()->select('url, date')->from('reviews r')->where('userId='.Yii::app()->user->getId().' AND date>'.$newRevTime)->queryRow();
            $maxCommentDate = Yii::app()->db->createCommand("SELECT max(`date`) FROM `reviews` WHERE `userId`=".Yii::app()->user->getId().' and partnerId='.$partner['partnerid'])->query()->read();
            $lastCommentDate = !empty($maxCommentDate['max(`date`)']) ? $maxCommentDate['max(`date`)'] : 0;
            $userIsWork = Yii::app()->db->createCommand()->select('id')->from('partners_users')->where('userId='.Yii::app()->user->getId().' and partnerId='.$partner['partnerid'])->queryRow();
        }
        $this->checkIsReviewModerator();
        $advertCode = Yii::app()->db->createCommand()->select('b.code')->from('banners_relations r')->join('banners b', 'b.bannerId=r.bannerId and b.type="Спонсор категории на главной" ')->where('r.catId='.$catId)->queryScalar();
        $this->render('profile', array('cat'=>$cat, 'advertCode'=>$advertCode, 'errorModel'=>$errorModel, 'userNewReview'=>!empty($userNewReview) ? $userNewReview : '', 'partner'=>$partner, 'model'=>$model, 'revRatings'=>$revRatings, 'partnersTextScore'=>!empty($partnersTextScore) ? $partnersTextScore : '',
            'reviews'=>$reviews, 'pagination'=>$pagination, 'lastCommentDate'=>!empty($lastCommentDate) ? $lastCommentDate : '', 'delegates'=>$delegates, 'userIsWork'=>!empty($userIsWork) ? $userIsWork : '', 'sortRatings'=>$sortRatings, 'relProfiles'=>$relProfiles, 'count'=>$count, 'subCats'=>$subCats));
    }
    
    public function actionPreview($url) {
        if(Yii::app()->user->isGuest) throw new CHttpException(404);
        $errorModel = new ErrorReporting();
        if(isset($_POST['ErrorReporting'])) {
            if($errorModel->save()) $this->refresh();
        }
        $model = Reviews::model()->with('user', 'images', 'revRatings')->findByAttributes(array('url'=>$url));
        if(empty($model)) throw new CHttpException(404);
        $this->checkIsReviewModerator();
        if(!$this->canModerRev && ( Yii::app()->user->getId() != $model->userId || $model->date+1200 < time() )) throw new CHttpException(404); 
        if(isset($_POST['Reviews'])) {
            $model->attributes = $_POST['Reviews'];
            if($model->validate()) {
                $model->status = 'Новый';
                $model->save(false);
                $this->redirect(array('profile/index', 'catId'=>$model['partner']['catId'], 'partnerUrl'=>$model['partner']['url']));    
            }
        }
        $partner = Yii::app()->db->createCommand()->select('p.fieldName, p.name, p.url, p.catId, p.partnerid, p.keywords, p.title, p.type, p.refLink')->from('partners p')->where('p.partnerid='.$model['partnerid'])->queryRow();
        $subCats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where('partnerid='.$partner['partnerid'])->queryAll();
        $cat = Yii::app()->db->createCommand()->select('catId, name, reviewRules, reviewRating1, reviewRating2, reviewRating3, reviewRating4, ratingRules')->from('partners_cat')->where("catId=".$partner['catId'])->queryRow();
        $this->brending('partner', $partner['partnerid'], $cat['catId']);
        $relProfiles = Yii::app()->db->createCommand()->select('*')->from('partners_relprofiles')->where("partnerid=".$partner['partnerid'])->queryAll();
        $revRatings = Yii::app()->db->createCommand()->select('*')->from('partners_ad_rev_rat')->where('catId='.$cat['catId'])->queryAll();
        $partnersTextScore = Yii::app()->db->createCommand()->select('rt.val, ps.title, ps.about, ps.scoreId')->from('partners_text_score ps')->leftJoin('reviews_text_ratings rt', 'rt.scoreId=ps.scoreId and revId='.$model->revId)->where('ps.partnerId='.$partner['partnerid'])->queryAll();
        $userIsWork = Yii::app()->db->createCommand()->select('id')->from('partners_users')->where('userId='.Yii::app()->user->getId().' and partnerId='.$partner['partnerid'])->queryRow();
        $advertCode = Yii::app()->db->createCommand()->select('b.code')->from('banners_relations r')->join('banners b', 'b.bannerId=r.bannerId and b.type="Спонсор категории на главной" ')->where('r.catId='.$cat['catId'])->queryScalar();
        $this->render('preview', array('subCats'=>$subCats, 'advertCode'=>$advertCode, 'model'=>$model, 'partner'=>$partner, 'cat'=>$cat, 'relProfiles'=>$relProfiles, 'errorModel'=>$errorModel, 'userIsWork'=>$userIsWork, 'revRatings'=>$revRatings, 'partnersTextScore'=>$partnersTextScore, 'partner'=>$partner, 'cat'=>$cat));
    }
    
    public function actionInvite($partnerUrl, $catId) {
        $errorModel = new ErrorReporting();
        if(isset($_POST['ErrorReporting'])) {
            if($errorModel->save()) $this->refresh();
        }
        $cat = Yii::app()->db->createCommand()->select('catId, name, parentId, reviewRules, reviewRating1, reviewRating2, reviewRating3, reviewRating4, ratingRules')->from('partners_cat')->where("catId=$catId")->queryRow();
        if(empty($cat)) throw new CHttpException(404, 'Не найдено указанной записи');
        $partner = Yii::app()->db->createCommand()->select('p.name, p.url, p.partnerid, p.keywords, p.title, p.about, p.catId, p.type')->from('partners p')->where('p.url="'.$partnerUrl.'" and p.catId='.$cat['catId'])->queryRow();
        if(empty($partner)) throw new CHttpException(404, 'Не найдено указанной записи');
        $this->brending('partner', $partner['partnerid'], $cat['catId']);
        $subCats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where('partnerid='.$partner['partnerid'])->queryAll();
        $relProfiles = Yii::app()->db->createCommand()->select('*')->from('partners_relprofiles')->where("partnerid=".$partner['partnerid'])->queryAll();
        $invites = Yii::app()->db->createCommand()->select('i.*, u.login as userLogin, u.userId as userId')->from('partners_invite i')->leftJoin('users u', 'u.userId=i.notWorkUser')->where('i.partnerid='.$partner['partnerid'])->queryAll();
        if(!Yii::app()->user->isGuest) $userIsWork = Yii::app()->db->createCommand()->select('id')->from('partners_users')->where('userId='.Yii::app()->user->getId().' and partnerId='.$partner['partnerid'])->queryRow();
        $advertCode = Yii::app()->db->createCommand()->select('b.code')->from('banners_relations r')->join('banners b', 'b.bannerId=r.bannerId and b.type="Спонсор категории на главной" ')->where('r.catId='.$cat['catId'])->queryScalar();
        $this->render('invite', array('subCats'=>$subCats, 'advertCode'=>$advertCode, 'partner'=>$partner, 'invites'=>$invites, 'cat'=>$cat, 'errorModel'=>$errorModel, 'userIsWork'=>!empty($userIsWork) ? $userIsWork : '', 'relProfiles'=>$relProfiles));
    }
    
    public function actionReview($url, $partnerUrl, $catId) {
        $model = new ReviewsComments();
        if(isset($_POST['ReviewsComments'])) {
            $model->attributes = $_POST['ReviewsComments'];
            if($model->save()) $this->refresh();
        }
        $errorModel = new ErrorReporting();
        if(isset($_POST['ErrorReporting'])) {
            if($errorModel->save()) $this->refresh();
        }
        $cat = Yii::app()->db->createCommand()->select('catId, name')->from('partners_cat')->where("catId=$catId")->queryRow();
        if(empty($cat)) throw new CHttpException(404, 'Не найдено указанной записи');
        $partner = Yii::app()->db->createCommand()->select('partnerid, url, about, name, type, delegate1, delegate2')->from('partners')->where("url=\"$partnerUrl\"")->queryRow();
        if(empty($partner)) throw new CHttpException(404, 'Не найдено указанной записи');
        $this->checkIsReviewModerator();
        $subCats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where('partnerid='.$partner['partnerid'])->queryAll();
        $relProfiles = Yii::app()->db->createCommand()->select('*')->from('partners_relprofiles')->where("partnerid=".$partner['partnerid'])->queryAll();
        $this->brending('partner', $partner['partnerid'], $cat['catId']);
        $rev = Yii::app()->db->createCommand()->select('r.*, u.login, u.displayName, u.userid, u.avatar, p.url as partnerUrl, p.delegate1, p.delegate2, pc.parentId as catParentId, pc.catId, pc.reviewRating1, pc.reviewRating2, pc.reviewRating3, pc.reviewRating4')->from('reviews r')->join('users u', 'u.userid=r.userId')->join('partners p', 'p.partnerid=r.partnerid')->join('partners_cat pc', 'pc.catId=p.catId')->where('r.url="'.$url.'"')->queryRow();
        if(empty($rev)) throw new CHttpException(404, 'Не найдено указанной записи');
        if(!Yii::app()->user->isGuest && Yii::app()->user->getId() == $rev['userid']) {
            Yii::app()->db->createCommand()->update('reviews_comments', array('isNew'=>'0'), 'revId='.$rev['revId']);
        }
        $revImg = Yii::app()->db->createCommand()->select('*')->from('reviews_images')->where('revId='.$rev['revId'])->queryAll();
        $revRatings = Yii::app()->db->createCommand()->select('*')->from('reviews_ratings')->where('revId='.$rev['revId'])->queryAll();
        
        $comments = Yii::app()->db->createCommand()->select('c.*, u.login, u.displayName, u.avatar, u.userid as comUid')->from('reviews_comments c')->join('users u', 'u.userId=c.userId')->where("revId=".$rev['revId'])->order('c.date DESC')->queryAll();
        if(!empty($comments)) {
            $idArr = array();
            foreach ($comments as $c) {
                if(!in_array($c['comUid'], $idArr))
                    $idArr[] = $c['comUid'];
            }
            $sql = 
            'SELECT 
                rc.userId, 
                count(DISTINCT r.revId) AS reviews, 
                count(DISTINCT nc.comId) AS newsComments, 
                count(DISTINCT fc.comId) AS forumComments, 
                count(DISTINCT rc.comId) AS revComments, 
                count(DISTINCT bc.id) AS blogComments
            FROM `reviews_comments` `rc`
                LEFT JOIN `news_comments` `nc` ON nc.userid = rc.userid
                LEFT JOIN `forum_comments` `fc` ON fc.userid = rc.userid
                LEFT JOIN `reviews` `r` ON r.userid = rc.userid
                LEFT JOIN `blog_comments` `bc` ON bc.userid = rc.userid
            WHERE rc.userid IN('.implode(',', $idArr).') GROUP BY rc.userId';
            $countMessagesData = Yii::app()->db->createCommand($sql)->query()->readAll();
        }
        if(!Yii::app()->user->isGuest) $userIsWork = Yii::app()->db->createCommand()->select('id')->from('partners_users')->where('userId='.Yii::app()->user->getId().' and partnerId='.$partner['partnerid'])->queryRow();
        $advertCode = Yii::app()->db->createCommand()->select('b.code')->from('banners_relations r')->join('banners b', 'b.bannerId=r.bannerId and b.type="Спонсор категории на главной" ')->where('r.catId='.$cat['catId'])->queryScalar();
        $this->render('review', array('model'=>$model, 'advertCode'=>$advertCode, 'countMessagesData'=>!empty($countMessagesData) ? $countMessagesData : 0, 'errorModel'=>$errorModel, 'subCats'=>$subCats, 'relProfiles'=>$relProfiles, 'userIsWork'=>!empty($userIsWork)?$userIsWork:'', 'partner'=>$partner, 'cat'=>$cat, 'comments'=>$comments, 'rev'=>$rev, 'revRatings'=>$revRatings, 'revImg'=>$revImg, 'userComment'=>!empty($userComment) ? $userComment : ''));
    }
    
    public function actionEditRevCom($id) {
        $model = new EditRevComForm();
        if(isset($_POST['EditRevComForm'])) {
            if($model->validate()) {
                Yii::app()->db->createCommand()->update('reviews_comments', array('text'=>$model->text), "comId=$id");
                $this->redirect(Yii::app()->createUrl('partner/profile/review', array('url'=>$_POST['url'], 'partnerUrl'=>$_POST['partnerUrl'], 'catId'=>$_POST['catId'])));
            }
        }
        $errorModel = new ErrorReporting();
        if(isset($_POST['ErrorReporting'])) {
            if($errorModel->save()) $this->refresh();
        }
        $this->checkIsReviewModerator();
        if(!$this->canModerRevCom) throw new CHttpException(404, 'Не найдено указанной записи');
        $review = Yii::app()->db->createCommand()->select('c.*, u.login, u.avatar, u.userid as comUid, p.partnerid, p.url as partnerUrl, p.type, p.catId, p.delegate1, p.delegate2, p.name as pName, r.url')->from('reviews_comments c')->join('reviews r', 'r.revId=c.revId')->join('partners p', 'p.partnerid=r.partnerId')->join('users u', 'u.userId=c.userId')->where('c.comId='.$id)->queryRow();
        if(empty($review)) throw new CHttpException(404, 'Не найдено указанной записи');
        $cat = Yii::app()->db->createCommand()->select('c.name, c.catId')->from('partners_cat c')->where('c.catId='.$review['catId'])->queryRow();
        $this->brending('partner', $review['partnerid'], $cat['catId']);
        $subCats = Yii::app()->db->createCommand()->select('c.name, c.catId, c.parentId, rc.partnerId')->from('partners_sub_cat_rel rc')->join('partners_cat c', 'c.catId=rc.catId')->where('partnerid='.$review['partnerid'])->queryAll();
        $relProfiles = Yii::app()->db->createCommand()->select('*')->from('partners_relprofiles')->where("partnerid=".$review['partnerid'])->queryAll();
        if(!Yii::app()->user->isGuest) $userIsWork = Yii::app()->db->createCommand()->select('id')->from('partners_users')->where('userId='.Yii::app()->user->getId().' and partnerId='.$review['partnerid'])->queryRow();
        $advertCode = Yii::app()->db->createCommand()->select('b.code')->from('banners_relations r')->join('banners b', 'b.bannerId=r.bannerId and b.type="Спонсор категории на главной" ')->where('r.catId='.$cat['catId'])->queryScalar();
        $this->render('editRevCom', array('review'=>$review, 'advertCode'=>$advertCode, 'model'=>$model, 'errorModel'=>$errorModel, 'userIsWork'=>!empty($userIsWork) ? $userIsWork : '', 'cat'=>$cat, 'relProfiles'=>$relProfiles, 'subCats'=>$subCats));
    }
}